/* Copyright (c) 2010 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.orkut.client.api.samples.greetings.client.selector;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
import com.google.inject.internal.Nullable;
import com.google.orkut.client.api.samples.greetings.client.selector.ItemSection.ItemSectionCallback;
import com.google.orkut.client.api.samples.greetings.client.selector.SearchBox.SearchBoxUserInputCallback;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Allows the building of a selector from various items. Derived classes should
 * implement {@link #getItemFor(Object)} which returns an {@link Item} for a given
 * object in the item selector.
 *
 * @author Shishir Birmiwal
 */
public abstract class ItemSelector<T> extends Composite implements SearchBoxUserInputCallback,
ItemSectionCallback {
  private static ItemSelectorUiBinder uiBinder = GWT.create(ItemSelectorUiBinder.class);

  interface ItemSelectorUiBinder extends UiBinder<Widget, ItemSelector> {
  }

  @UiField
  ItemSection itemSection;

  @UiField(provided = true)
  protected SearchBox searchBox;

  @UiField
  FlowPanel container;

  @UiField
  Label clearFloat;

  public HashMap<T, Item> items;
  private boolean searchBoxEnabled;

  @Inject
  public ItemSelector(@Nullable SearchBox searchBox) {
    this.searchBox = searchBox;
    items = new HashMap<T, Item>();
    if (searchBox != null) {
      searchBox.setCallback(this);
      searchBox.setVisible(false);
    }
    initWidget(uiBinder.createAndBindUi(this));
    itemSection.setCallback(this);
  }

  @Override
  public void setTitle(String text) {
    itemSection.setTitle(text);
  }

  private void insertItem(Item item) {
    container.insert(item, container.getWidgetCount() - 1);
  }

  private void removeItem(Item item) {
    container.remove(item);
  }

  public void clear() {
    items.clear();
    container.clear();
    container.add(clearFloat);
  }

  public void updateItems(ArrayList<T> newValues) {
    ArrayList<T> valuesToAdd = new ArrayList<T>();
    ArrayList<T> valuesToRemove = new ArrayList<T>();

    for (T newValue : newValues) {
      if (items.containsKey(newValue)) {
        continue;
      }
      valuesToAdd.add(newValue);
    }

    for (T oldValue : items.keySet()) {
      if (newValues.contains(oldValue)) {
        continue;
      }
      valuesToRemove.add(oldValue);
    }

    for (T value : valuesToAdd) {
      Item item = getItemFor(value);
      items.put(value, item);
      insertItem(item);
    }

    for (T value : valuesToRemove) {
      removeItem(items.remove(value));
    }
  }

  abstract protected Item getItemFor(T value);


  public void collapse() {
    itemSection.collapse();
  }

  public void expand() {
    itemSection.expand();
  }

  @Override
  public void collapsed() {
    if (searchBox != null) {
      searchBox.setVisible(false);
    }
  }

  @Override
  public void expanded() {
    if (searchBox != null) {
      searchBox.resetPrompt();
      searchBox.setVisible(isSearchBoxEnabled());
      searchBox.setFocus(isSearchBoxEnabled());
    }
  }

  @Override
  public void enterPressed(String searchString) {
    Item selectedItem = null;
    for (Item item : items.values()) {
      if (item.isVisible()) {
        if (selectedItem != null) {
          return;
        }
        selectedItem = item;
      }
    }
    selectedItem.click();
  }

  @Override
  public void searchStringUpdated(String searchString) {
    if (searchBoxEnabled) {
      String key = searchString.toLowerCase();
      for (Item item : items.values()) {
        item.setVisible(item.searchKey.toLowerCase().contains(key));
      }
    }
  }

  public void setSearchBoxEnabled(boolean searchBoxEnabled) {
    this.searchBoxEnabled = searchBoxEnabled;
    searchBox.setVisible(container.isVisible() && searchBoxEnabled);
  }

  public boolean isSearchBoxEnabled() {
    return searchBoxEnabled;
  }
}